//
//  YSReadView.m
//  YSBookRead
//
//  Created by MOLBASE on 2018/11/8.
//  Copyright © 2018年 YangShen. All rights reserved.
//

#import "YSReadView.h"
#import "YSReaderSetting.h"

@implementation YSReadViewCell

+ (instancetype)cellWithTableView:(UITableView *)tableView {
    static NSString *ID = @"YSReadViewCell";
    YSReadViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[YSReadViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = [UIColor clearColor];
        [self setupSubViews];
    }
    return self;
}

- (void)setupSubViews {
    self.readView = [[YSReadView alloc] init];
    self.readView.frame = CGRectMake(0, 0, YSReaderFrame().size.width, YSReaderFrame().size.height);
    self.readView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.readView];
}

@end

@implementation YSReadView

- (void)setContentFrame:(CTFrameRef)contentFrame {
    if (_contentFrame) {
        CFRelease(_contentFrame);
    }
    _contentFrame = contentFrame;
    [self setNeedsDisplay];
}

- (void)dealloc {
    if (_contentFrame) {
        CFRelease(_contentFrame);
    }
}

- (void)setContent:(NSAttributedString *)content {
    _content = content;
    CTFramesetterRef setterRef = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)content);
    CGPathRef pathRef = CGPathCreateWithRect(self.bounds, NULL);
    CTFrameRef frameRef = CTFramesetterCreateFrame(setterRef, CFRangeMake(0, 0), pathRef, NULL);
    if (setterRef) {
        CFRelease(setterRef);
    }
    if (pathRef) {
        CFRelease(pathRef);
    }
    self.contentFrame = frameRef;
}

- (void)drawRect:(CGRect)rect {
    if (!_contentFrame) {
        return;
    }
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
    CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    CTFrameDraw(_contentFrame, ctx);
}

@end
